package com.example.comsumer;

import com.netflix.discovery.DiscoveryManager;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author 吕一明
 * @公众号 码客在线
 */
@RestController
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    OrderClient orderClient;


    @HystrixCommand(fallbackMethod = "testFallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.strategy", value="THREAD"),// 隔离方式 [THREAD, SEMAPHORE]
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
    })
    @GetMapping("test")
    public String test() {
        logger.info("----------------->test");
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject("http://localhost:8088/producter/order/1", String.class);
        return result;
    }

    public String testFallback() {
        return "testFallback";
    }

    @GetMapping("/shutdown")
    public String shutdown() {
        DiscoveryManager.getInstance().shutdownComponent();
        return "下线成功";
    }

    @GetMapping("/test2")
    public String test2() {

        // 1、选择一个eureka节点
        // 2、拉群所有的被调用端的应用列表
        // 3、根据算法选择出其中一个节点返回
        ServiceInstance instance = loadBalancerClient.choose("PRODUCTER-CLIENT");

        String url = "http://"+instance.getHost()+":"+ instance.getPort() +"/order/2";

        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);

        return result;
    }

    @GetMapping("/test3")
    public String test3() {
        return orderClient.findById(3L);
    }

    @GetMapping("/test4")
    public String test4() {
        return restTemplate.getForObject("http://PRODUCTER-CLIENT/order/4", String.class);
    }

}
